package org.tis.tools.abf.module.common.validation;

import com.alibaba.druid.util.StringUtils;
import org.tis.tools.abf.module.sys.entity.vo.SysDictApiDetail;
import org.tis.tools.abf.module.sys.service.ISysDictService;
import org.tis.tools.core.utils.SpringUtil;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.List;

/**
 * description: tools业务字典约束校验类
 *
 * 对应{@link org.tis.tools.abf.module.sys.entity.SysDict}
 * @author zhaoch
 * @date 2018/9/5
 **/
public class DictValidatorHandler  implements ConstraintValidator<Dict, String> {

    /**
     * 业务字典项key值
     * 对应{@link org.tis.tools.abf.module.sys.entity.SysDict#dictKey}
     */
    private String dictKey;

    /**
     * Implements the validation logic.
     * The state of {@code value} must not be altered.
     * <p>
     * This method can be accessed concurrently, thread-safety must be ensured
     * by the implementation.
     *
     * @param value   object to validate
     * @param context context in which the constraint is evaluated
     * @return {@code false} if {@code value} does not pass the constraint
     */
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {

        if (value == null) {
            return true;
        }
        // TODO 使用缓存获取字典值，目前通过查询数据库实现
        ISysDictService sysDictService = SpringUtil.getBean(ISysDictService.class);
        List<SysDictApiDetail> sysDictApiDetails = sysDictService.queryDictSon(dictKey);
        return sysDictApiDetails.stream().anyMatch(s -> StringUtils.equals(s.getDictKey(), value));
    }

    /**
     * Initializes the validator in preparation for
     * {@link #isValid(Object, ConstraintValidatorContext)} calls.
     * The constraint annotation for a given constraint declaration
     * is passed.
     * <p>
     * This method is guaranteed to be called before any use of this instance for
     * validation.
     * <p>
     * The default implementation is a no-op.
     *
     * @param constraintAnnotation annotation instance for a given constraint declaration
     */
    @Override
    public void initialize(Dict constraintAnnotation) {
        // 获取对应业务字典的key值
        this.dictKey = constraintAnnotation.value();
    }
}
